<template>
  <el-config-provider :size="globalComSize" :locale="zhCn">
    <router-view></router-view>
    <!-- <WatchLogin /> -->
  </el-config-provider>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue'
  import { useSettingStore } from '@/store/modules/setting'
  import zhCn from 'element-plus/es/locale/lang/zh-cn'
  import timeoutReLogin from './utils/timeoutReLogin'
  import { useUserStore } from './store/modules/user'
  import { initWebSocket } from './utils/socket'
  import { ElMessageBox } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { useSetIsUserStaySystem } from '@/services/common/useUserState'
  import { getCustomerCode, getSSOUserInfo } from './api/user'
  import useCurrentRoleStore from '@/store/modules/current-role'
  import useRequestHeaderFromQueryParamStore from '@/store/modules/request-header-from-query-param'

  const { setCurrentRole } = useCurrentRoleStore()
  const { requestHeaderFromQueryParam, setRequestHeaderFromQueryParam } =
    useRequestHeaderFromQueryParamStore()

  const SettingStore = useSettingStore()
  const userStore = useUserStore()
  const globalComSize = computed((): string => SettingStore.themeConfig.globalComSize)
  const router = useRouter()

  /**
   * 单点登录
   * 原本系统的登录是先输入账号和密码登录，在获取企业，点击企业进入到系统内
   * 上面的这些步骤都是手动的，现在改为编码的方式帮用户自动完成
   */
  const ssoInit = async () => {
    const res = await getSSOUserInfo({
      'RSA-TOKEN': requestHeaderFromQueryParam['RSA-TOKEN'],
      LINK: requestHeaderFromQueryParam['LINK'],
    })
    if (res.data.code === 20000) {
      const { loginCustomerVo, accountLoginToken } = res.data.data.resp
      userStore.row = { ...accountLoginToken, tokenStartTime: new Date().getTime() }
      initWebSocket(function funGetmrg(msg: any) {
        if (msg.code == 40102) {
          userStore.token = ''
          userStore.roles = []
          userStore.row = {
            tokenValue: '', //登录token
            expireIn: null, //过期时间
            tokenStartTime: null, //登录当前时间
            refreshToken: '', //刷新token
            tokenName: '',
          }
          ElMessageBox.confirm(msg.message, '提示', {
            confirmButtonText: '确定',
            type: 'error',
            showCancelButton: false,
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
          }).then(async () => {
            userStore.logout()
            router.push({ path: '/login/index' })
          })
        }
      }, `/ws/login/${useUserStore().row.tokenValue}`)
      useSetIsUserStaySystem(true)
      userStore.account = loginCustomerVo.phone
      userStore.role = loginCustomerVo.customerRoleVos
      if (loginCustomerVo.customerRoleVos.length >= 1 && loginCustomerVo.customerRoleVos[0]) {
        const firstRole = loginCustomerVo.customerRoleVos[0]
        if (firstRole.status === 2) {
          const res = await getCustomerCode({ code: firstRole.code })
          if (res.data.success) {
            userStore.token = userStore.row.tokenValue
            userStore.getInfo()
            setCurrentRole(firstRole)
          }
        }
      }
      router.push(res.data.data.resp.link)
    }
  }

  onMounted(() => {
    setRequestHeaderFromQueryParam()
    if (
      requestHeaderFromQueryParam &&
      Object.keys(requestHeaderFromQueryParam).includes('RSA-TOKEN') &&
      !userStore.token
    ) {
      ssoInit()
    }
    timeoutReLogin()

    window.addEventListener('vite:preloadError', () => {
      window.location.reload()
    })
  })
</script>

<style lang="scss">
  #app {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .el-pager li:focus {
    border: none;
  }
  .el-dropdown:focus {
    border: none;
  }
  .svg-icon:focus {
    border: none;
  }
</style>
